package com.study.messagebus.init

import android.app.Activity
import android.app.Application
import android.os.Bundle
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.LifecycleOwner
import com.study.messagebus.Register
import com.study.messagebus.core.MessageBus

object Init {
    lateinit var context: Application

    fun init(context: Application) {
        Init.context = context
        registerLifeCircle()
    }

    /**
     * 注册监听所有activity的生命周期
     * 注册fragment的监听
     * getSupportFragmentManager().registerFragmentLifecycleCallbacks(mFragmentLifecycleCallbacks,true);
     */
    private fun registerLifeCircle() {
        context.registerActivityLifecycleCallbacks(object :
            Application.ActivityLifecycleCallbacks {
            override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
                //在被注解的activity上注册MessageBus
                if (activity is LifecycleOwner && activity::class.java.isAnnotationPresent(Register::class.java)) {
                    MessageBus.register(activity)
                }

                if (activity is FragmentActivity) {
                    activity.supportFragmentManager.registerFragmentLifecycleCallbacks(
                        object : FragmentManager.FragmentLifecycleCallbacks() {
                            override fun onFragmentCreated(
                                fm: FragmentManager,
                                fragment: Fragment,
                                savedInstanceState: Bundle?
                            ) {
                                //在被注解的activity上注册MessageBus
                                if (fragment::class.java.isAnnotationPresent(Register::class.java)) {
                                    MessageBus.register(fragment)
                                }
                            }
                        }, true
                    )
                }
            }

            override fun onActivityStarted(activity: Activity) {}

            override fun onActivityResumed(activity: Activity) {}

            override fun onActivityPaused(activity: Activity) {}

            override fun onActivityStopped(activity: Activity) {}

            override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {}

            override fun onActivityDestroyed(activity: Activity) {}
        })
    }
}